﻿using System;

using Gonte.Reflection;
using Gonte.Xml.Serialization;
using System.Reflection;

namespace Gonte.Collections
{
    internal class StringKeyDictionaryDeserializer
        : XmlDictionaryDeserializer
    {
        #region Constructors

        internal StringKeyDictionaryDeserializer(Object @object)
            : base(@object)
        {
        }

        #endregion

        #region Overridables

        protected override Object CreateItem()
        {
            Object parent = context_.Parent;
            PropertyInfo propertyInfo = parent.GetType().GetProperty(context_.PropertyName);
            attribute_ = CustomAttribute.GetCustomAttribute<DictionaryItemAttribute>(propertyInfo, false);
            ExceptionThrower.ThrowWhenNull("DictionaryItemAttribute", attribute_);

            Type itemType;

            if (attribute_.ValueType != null) // Use the field of the attribute
            {
                itemType = attribute_.ValueType;
            }
            else
            {
                Type type = object_.GetType();
                itemType = type.GetGenericArguments()[0];
            }

            if (PrimitiveType.IsPrimitive(itemType))
            {
                DictionaryItemPrimitive itemPrimitive = new DictionaryItemPrimitive();
                itemPrimitive.Key = string.Empty;
                itemPrimitive.Value = CreateItem(itemType);

                return itemPrimitive;
            }

            return CreateItem(itemType); // Create the value
        }

        #endregion
    }
}
